/**
 * 撤回弹出框
 */
import { Button, Input, Form, Modal, Select } from "antd";
import { forwardRef, useImperativeHandle, useState, useRef, useLayoutEffect, useEffect } from "react";
import request from "../../framework/common/utils/request";
import { useForm } from "../../framework/common/context/metadata-context";
import { message } from "antd";
import { getQuery } from "../../framework/common/utils";
import md5 from "js-md5";
import { globalModule } from "../../approval/index.js";
const { TextArea } = Input;

export default forwardRef(function ({}, ref) {
  const { data: tplData, urlPrefix, params } = useForm().root;
  const [isVisible, setIsVisible] = useState(false);
  function showModal() {
    setIsVisible(true);
  }
  useImperativeHandle(ref, () => {
    return {
      showModal,
    };
  });
  return (
    <>{isVisible && <ModalContent urlPrefix={urlPrefix} tplData={tplData} params={params} isVisible={isVisible} setIsVisible={setIsVisible}></ModalContent>}</>
  );
});

const ModalContent = function ({ isVisible, setIsVisible, tplData, urlPrefix, params }) {
  const [form] = Form.useForm();
  const [btnLoading, setBtnLoading] = useState(false);
  let test = new Array(1024 * 1024 * 1024);
  //获取当前步骤的审批人
  let withdrawValue = "";
  useEffect(() => {
    if (tplData.BusinessButtons && tplData.BusinessButtons.MoreButtonList) {
      tplData.BusinessButtons.MoreButtonList.find(function (item) {
        if (item.OperationCode && item.OperationCode == "Withdraw") {
          if (item.WithdrawReason && item.WithdrawReason.length > 0) {
            withdrawValue = item.WithdrawReason;
          }
          return true;
        }
      });
    }
    if (tplData.flowOperationNameMap && tplData.flowOperationNameMap.length && tplData.flowOperationNameMap[6]) {
      withdrawValue = tplData.flowOperationNameMap[6].defaultOpinion;
    }
  }, []);

  function handleOk(options) {
    form.validateFields()
      .then((values) => {
        let formData = form.getFieldsValue();

        let sendData = {
          node_id: params.node_id,
          proc_id: params.proc_id,
          business_id: params.business_id,
          opinion: formData.withdraw, //撤回原因
          manual_execution: false,
          form_data: {
            children: tplData.form.form_data.children,
            fieldSources: tplData.form.form_data.fieldSources,
            main: tplData.form.form_data.main,
            attachmentTypes: tplData.form.form_data.attachmentTypes,
          },
        };
        let requestOption = {
          url: "/flowinstance/approval/withdraw?prc_name=" + tplData.ProcessInfo.Title,
          method: "POST",
          data: sendData,
          noTip: true//请求错误时，axios不展示公共错误
        };
        //options = {manual_execution:true}
        if (options && options.manual_execution === true) {
          //如果是人工确认的，再请求一次
          sendData.manual_execution = true;
          requestOption.headers = {
            vtk: md5(JSON.stringify(sendData)),
          };
        }
        setBtnLoading(true);
        request(requestOption)
          .then(function (result) {
            setBtnLoading(false);
            if (result.code == 1) {
              message.success("撤回成功");
              setIsVisible(false);
              globalModule.refreshParentWindow({
                tplData: tplData,
                approveType: "Withdraw",
              }); //撤回后回调刷新业务系统的方法
              setTimeout(function () {
                var href = "";
                if (result.data.ProcessInstanceStatus == -3) {
                  href = "/flowinstance/process/create?proc_id=" + tplData.ProcessInfo.ProcessGuid;
                } else if (result.data.ProcessInstanceId) {
                  href =
                    "/flowinstance/approval/index?node_id=" +
                    result.data.TaskId +
                    "&proc_id=" +
                    result.data.ProcessInstanceId +
                    "&package_id=" +
                    result.data.PackageId;
                } else {
                  href =
                    "/flowinstance/approval/index?node_id=" +
                    tplData.NodeInfo.node_id +
                    "&proc_id=" +
                    tplData.ProcessInfo.ProcessGuid +
                    "&package_id=" +
                    params.package_id;
                }
                if (urlPrefix) {
                  href = urlPrefix + href;
                }

                //撤回后的链接也带上第三方OA审批后动作参数
                let urlParams = getQuery();
                if (urlParams.afterApprove) {
                  href = href + "&afterApprove=" + urlParams.afterApprove;
                }
                var handledClose = urlParams.handledclose || urlParams.handledClose;
                if (typeof handledClose != "undefined" && handledClose.toLowerCase() == "true") {
                  href = href + "&handledClose=" + handledClose;
                }

                window.location.href = href;
              }, 602);
            } else if (result.code == 34001) {
              //手工确认再次发送请求，用于操作前后二开的确认框 //result.code == 30000 可以用30000来测试校验
              Modal.destroyAll(); //给出提示前，先清掉所有弹框
              Modal.confirm({
                title: "提示",
                content: result.message, //result.message
                centered: true,
                confirmLoading: true,
                okText: "确认",
                cancelText: "取消",
                onCancel: function () {
                  setIsVisible(false);
                },
                onOk: function () {
                  return new Promise(function (resolve, reject) {
                    handleOk({
                      manual_execution: true,
                    });
                  });
                },
              });
            } else {
              message.error(result.message);
            }
          })
          .catch(function () {
            setBtnLoading(false);
            message.error("撤回失败");
          });
      })
      .catch((errorInfo) => {
        setBtnLoading(false);
        return;
      });

    // form.validateFields(function(errors,values){
    //   if(errors){//如果存在校验不通过，不做请求

    //   }

    // });
  }

  const handleCancel = () => {
    setIsVisible(false);
  };

  // const { getFieldDecorator } = form;

  //表单对齐方式
  const formLayout = "vertical";
  const formItemLayout = null;

  return (
    <Modal
      centered={true}
      title="撤回"
      width={600}
      visible={isVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={btnLoading} onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form} labelAlign={"left"}
            colon={false} layout={formLayout}>
          <Form.Item
            name="withdraw"
            initialValue={withdrawValue}
            rules={[
              {
                required: true,
                message: "请录入撤回内容",
              },
            ]}
            {...formItemLayout}
          >
            <TextArea showCount={true} rows="11" maxLength={1000} placeholder="请录入撤回内容"></TextArea>
          </Form.Item>
        </Form>
    </Modal>
  );
};
